//
//  MapGPSViewController.m
//  DataStatistics
//
//  Created by oilklenze on 15/11/3.
//  Copyright © 2015年 YTYangK. All rights reserved.

//列表gps
#import "Annotation.h"
#import "CanlloutAnnotationView.h"
#import "JZLocationConverter.h"
#import "KCAnnotation.h"
#import "MapGPSViewController.h"
#import <pop/POP.h>
#import "MapGPSModel.h"
#import "MapGPSViewModel.h"

@interface MapGPSViewController () <MKMapViewDelegate> {

    GPSSingleDetails* gpsSingleDetails;
    CLGeocoder* _geocoder;
    BOOL _firstDisplay;
}

@property (strong, nonatomic) CLLocationManager      * locationMangager;
@property (strong, nonatomic) NSMutableArray         * annotationaArray;
@property (nonatomic        ) CLLocationCoordinate2D coordinate;
@property (nonatomic, strong) CanlloutAnnotationView * annotationView;
@end

@implementation MapGPSViewController

#pragma mark 生命周期
- (void)viewDidLoad
{

    [self setTitle:@"GPS"];
    _firstDisplay = YES;
    [super viewDidLoad];
    //生成mapview
    [self.view addSubview:self.mapview];
    [self.mapview mas_makeConstraints:^(MASConstraintMaker* make) {
        make.left.equalTo(self.view).with.offset(0);
        make.right.equalTo(self.view).with.offset(0);
        make.bottom.equalTo(self.view).with.offset(0);
        make.top.equalTo(self.view).with.offset(0);
    }];
    //自己位置图标
    [self addmyLocation];
    _mapview.delegate = self;
    _locationMangager = [[CLLocationManager alloc] init];
    if (SYSTEM_VERSION_LESS_THAN(@"8.0")) {
        [_locationMangager startUpdatingLocation];
    }
    else {
        [self authorizationStatus];
    }
    _mapview.userTrackingMode = MKUserTrackingModeFollow;
    _mapview.mapType = MKMapTypeStandard;
    [self dataRequest];
}

#pragma mark - custom method 自定义方法
- (BOOL)authorizationStatus{
    if (!([CLLocationManager authorizationStatus] == kCLAuthorizationStatusAuthorizedWhenInUse) && !([CLLocationManager authorizationStatus] == kCLAuthorizationStatusAuthorizedAlways)) {
        [_locationMangager requestWhenInUseAuthorization];
        UIAlertController *authorizationStatusAler =[UtilToolsClss addAlertControllerForAuthorizationStatus:NSLocalizedString(@"请打开系统设置中\"隐私->定位->服务\",允许\"Oilklenze\"使用您的位置", nil) ];
        [self presentViewController:authorizationStatusAler animated:YES completion:nil];
        return NO;
    }else {
        return YES;
    }
}


//数据处理并添加大头针
- (void)dataRequest
{
//    NSString* urlString1 = [NSString stringWithFormat:@"deviceList/queryDeviceGps.asp"];
    
//    NSString* urlString  = [IPHEAD stringByAppendingString:urlString1];
//    AFHTTPRequestOperationManager* manager = [AFHTTPRequestOperationManager manager];
//    manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"text/html", nil];
//    NSDictionary* parameters = @{
//                                 @"deviceCode" : self.mapDeviceCode
//                                 };
//    [manager POST:urlString
//       parameters:parameters
//          success:^(AFHTTPRequestOperation* _Nonnull operation, id _Nonnull responseObject) {
//        if ([responseObject isKindOfClass:[NSDictionary class]]) {
//            gpsSingleDetails = [[GPSSingleDetails alloc] initWithDictionary:responseObject error:nil];
//    
//            [self addAnnotation];
//        }
//    }
//        failure:^(AFHTTPRequestOperation* _Nullable operation, NSError* _Nonnull error) {
//            if (error.code == -1004) {
//                [MBProgressHUD showError:NET_ERROR];
//            }
//            else {
//                [MoreViewController logout:self];
//            }
//        }];
    
    
    [MapGPSViewModel requestWithUrlForLoginIn:self andParam:@{@"deviceCode":self.mapDeviceCode} success:^(MapGPSModel *model) {
        
        KCAnnotation* annotation     = [[KCAnnotation alloc] init];
        annotation.c_name            = model.c_name;
        annotation.deviceCode        = model.deviceCode;
        annotation.upload_time       = model.upload_time;
        annotation.running_state     = model.running_state;
        CLLocationCoordinate2D Gcj02 = [JZLocationConverter wgs84ToGcj02:CLLocationCoordinate2DMake(model.latitude, model.longitude)];
                
        annotation.coordinate        = Gcj02;
        self.coordinate              = Gcj02;
        
        if (gpsSingleDetails.body.running_state == 1) {
            annotation.icon = [UIImage imageNamed:@"在线标记"];
        }
        else {
            annotation.icon = [UIImage imageNamed:@"离线标记"];
        }
        if (Gcj02.latitude != 0.0f && Gcj02.longitude !=0.0f) {
            [self.mapview addAnnotation:annotation];
            [self.annotationaArray addObject:annotation];
            _firstDisplay ? [self.mapview showAnnotations:self.annotationaArray animated:YES] :nil;
            _firstDisplay = NO;
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.2 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                CLLocationCoordinate2D newCoordinate =     [self mapCenterCoordinate:annotation.coordinate withOffsetXPixelSize:CGSizeMake(-60, 0)];
                [self.mapview setCenterCoordinate:newCoordinate animated:YES];
            });
            
        }
    
        
    } failure:^(NSString *error) {
        
        [MBProgressHUD yty_showErrorWithTitle:nil detailsText:error toView:nil];
    }];
    
    
}

//数据处理并添加大头针
//- (void)addAnnotation
//{
//    KCAnnotation* annotation     = [[KCAnnotation alloc] init];
//    annotation.c_name            = gpsSingleDetails.body.c_name;
//    annotation.deviceCode        = gpsSingleDetails.body.deviceCode;
//    annotation.upload_time       = gpsSingleDetails.body.upload_time;
//    annotation.running_state     = gpsSingleDetails.body.running_state;
//    CLLocationCoordinate2D Gcj02 = [JZLocationConverter wgs84ToGcj02:CLLocationCoordinate2DMake(gpsSingleDetails.body.latitude, gpsSingleDetails.body.longitude)];
//    
//    NSLog(@"%.2f,%.2f",gpsSingleDetails.body.latitude, gpsSingleDetails.body.longitude);
//    
//    annotation.coordinate        = Gcj02;
//    self.coordinate              = Gcj02;
//    if (gpsSingleDetails.body.running_state == 1) {
//        annotation.icon = [UIImage imageNamed:@"在线标记"];
//    }
//    else {
//        annotation.icon = [UIImage imageNamed:@"离线标记"];
//    }
//    if (Gcj02.latitude != 0.0f && Gcj02.longitude !=0.0f) {
//        [self.mapview addAnnotation:annotation];
//        [self.annotationaArray addObject:annotation];
//        _firstDisplay ? [self.mapview showAnnotations:self.annotationaArray animated:YES] :nil;
//        _firstDisplay = NO;
//        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.2 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
//            CLLocationCoordinate2D newCoordinate =     [self mapCenterCoordinate:annotation.coordinate withOffsetXPixelSize:CGSizeMake(-60, 0)];
//            [self.mapview setCenterCoordinate:newCoordinate animated:YES];
//        });
//
//    }
//   
//    
//
//
//}

//设置定位自己按钮
- (void)addmyLocation
{
    UIButton* myLocation = [UIButton buttonWithType:UIButtonTypeCustom];
    //    [myLocation.layer  setCornerRadius:31];
    [myLocation setBackgroundImage:[UIImage imageNamed:@"标记按钮"] forState:UIControlStateNormal];
    [myLocation addTarget:self action:@selector(clickButton:) forControlEvents:UIControlEventTouchUpInside];
    [self.mapview addSubview:myLocation];
    [myLocation mas_makeConstraints:^(MASConstraintMaker* make) {
        make.left.equalTo(self.mapview).with.offset(10);
        make.bottom.equalTo(self.mapview).with.offset(-35);
        make.height.mas_equalTo(@62);
        make.width.mas_equalTo(@62);
    }];
}



//点击按钮显示自己位置
- (void)clickButton:(UIButton*)button

{
    if (!self.mapview.userLocation.location) {
        return;
    }
    if ([self authorizationStatus]) {
        CLLocationCoordinate2D coord = self.mapview.userLocation.coordinate;
        MKCoordinateSpan span = { 0.01, 0.01 };
        MKCoordinateRegion region = { coord, span };
        [self.mapview setRegion:region animated:YES];
        
    }

}

//计算地图按像素位移
- (CLLocationCoordinate2D)mapCenterCoordinate:(CLLocationCoordinate2D)centerCoordinate withOffsetXPixelSize:(CGSize)size
{
    CGFloat pixelsPexDegreeLet = SCREEN_HEIGHT-64 / self.mapview.region.span.latitudeDelta;
    CGFloat pixelsPerDegreeLon = SCREEN_WIDTH / self.mapview.region.span.longitudeDelta;
    
    CLLocationDegrees offsetLonDegree = size.width / pixelsPerDegreeLon;
    CLLocationDegrees offsetLatDegree = size.height / pixelsPexDegreeLet;
    CLLocationCoordinate2D newCoordinate = {
        centerCoordinate.latitude + offsetLatDegree,
        centerCoordinate.longitude + offsetLonDegree
    };
    return newCoordinate;
}



#pragma mark - 代理
#pragma mark MapViewDeledate
//地图控件代理方法显示大头针是调用
- (MKAnnotationView*)mapView:(MKMapView*)mapView viewForAnnotation:(id<MKAnnotation>)annotation
{

    if ([annotation isKindOfClass:[KCAnnotation class]]) {

        static NSString* identifier = @"CustAnnotation";

        self.annotationView = (CanlloutAnnotationView*)[self.mapview dequeueReusableAnnotationViewWithIdentifier:identifier];
        if (self.annotationView == nil) {
            self.annotationView = [[CanlloutAnnotationView alloc] initWithAnnotation:annotation reuseIdentifier:identifier];
        }
        self.annotationView.annotation     = (KCAnnotation*)annotation;
        self.annotationView.image          = ((KCAnnotation*)annotation).icon;
        self.annotationView.enabled        = YES;
        self.annotationView.canShowCallout = NO;
        self.annotationView.centerOffset   = CGPointMake(0, 0);
        [self.annotationView setSingleLabelText:(KCAnnotation*)annotation];
        return self.annotationView;
    }
    else {
        return nil;
    }
}



//代理方法用户位置改变后触发----这里我是设置展示范围
//- (void)mapView:(MKMapView*)mapView didUpdateUserLocation:(nonnull MKUserLocation*)userLocation
//{
//    NSLog(@"==========>>>打印大头针%@", self.mapview.annotations);
//    if (_firstDisplay)
//    {
//        NSMutableArray* myarray = [self.annotationaArray mutableCopy];
////        [myarray addObject:self.mapview.userLocation];
//        [self.mapview showAnnotations:myarray animated:YES];
//        _firstDisplay = NO;
//    }
//}
//出来就显示大头针上面的view
- (void)mapView:(MKMapView*)mapView didAddAnnotationViews:(nonnull NSArray<MKAnnotationView*>*)views
{

    for (id myAnnotation in mapView.annotations) {
        //        id myAnnotation =[views objectAtIndex:0];
        if (![myAnnotation isKindOfClass:[MKUserLocation class]]) {
            [mapView selectAnnotation:myAnnotation animated:YES];
        }
    }
}

- (void)mapView:(MKMapView*)mapView didSelectAnnotationView:(MKAnnotationView *)view
{
    POPSpringAnimation* anim = [POPSpringAnimation animationWithPropertyNamed:kPOPViewFrame];
    anim.fromValue           = [NSValue valueWithCGRect:CGRectMake(-30 * 0.68, -7.5, 30, 8)];
    anim.toValue             = [NSValue valueWithCGRect:CGRectMake(-300 * 0.68, -80, 300, 80)];
    anim.springBounciness    = 10;
    anim.springSpeed         = 5;
    [self.annotationView.view pop_addAnimation:anim forKey:nil];
    [AddressView getAddressByLatitude:view.annotation.coordinate.latitude longitude:view.annotation.coordinate.longitude  addrees:^(NSString *placemark) {
        
        [self.addresView labelSetAddress:placemark];
        NSLog(@"---%@",placemark);
    }];
    [self.addresView addAppearAnimationByBeginFrame:self.addresView.frame finishFrame:CGRectMake(20, 0, self.addresView.size.width, self.addresView.size.height)];
}



//弹窗选项导航地图 没有激活此方法 可以删除
- (void)mapNavigationBtn:(UIButton*)button
{
    NSString* title                   = [NSString stringWithFormat:NSLocalizedString(@"导航到设备", nil)];
    UIAlertController* alerController = [UIAlertController alertControllerWithTitle:title
                                                                            message:nil
                                                                     preferredStyle:UIAlertControllerStyleActionSheet];
    UIAlertAction* cancelAction       = [UIAlertAction actionWithTitle:NSLocalizedString(@"cancel",nil)
                                                                 style:UIAlertActionStyleCancel handler:nil];
    UIAlertAction* gaodeMapAction     = [UIAlertAction actionWithTitle:NSLocalizedString(@"高德地图",nil)
                                                                 style:UIAlertActionStyleDefault
                                                               handler:^(UIAlertAction* _Nonnull action) {
        NSString* urlsting = [[NSString stringWithFormat:@"iosamap://navi?sourceApplication= &backScheme= &lat=%f&lon=%f&dev=0&style=2", self.coordinate.latitude, self.coordinate.longitude]
                              stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
        [[UIApplication sharedApplication] openURL:[NSURL URLWithString:urlsting]];

    }];

    CLLocationCoordinate2D bd09   = [JZLocationConverter gcj02ToBd09:self.coordinate];
    UIAlertAction* baiduMapAction = [UIAlertAction actionWithTitle:NSLocalizedString(@"百度地图",nil)
                                                             style:UIAlertActionStyleDefault
                                                           handler:^(UIAlertAction* _Nonnull action) {
    NSString* urlsting            = [[NSString stringWithFormat:@"baidumap://map/direction?origin={{我的位置}}&destination=latlng:%f,%f|name=目的地&mode=driving&coord_type=gcj02", self.coordinate.latitude, self.coordinate.longitude] stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
        [[UIApplication sharedApplication] openURL:[NSURL URLWithString:urlsting]];

    }];

    UIAlertAction* googleMapAction = [UIAlertAction actionWithTitle:NSLocalizedString(@"Google地图",nil)
                                                              style:UIAlertActionStyleDefault
                                                            handler:^(UIAlertAction* _Nonnull action) {
    NSString* urlsting             = [[NSString stringWithFormat:@"comgooglemaps://?x-source= &x-success= &saddr=&daddr=%f,%f&directionsmode=driving", self.coordinate.latitude, self.coordinate.longitude] stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
        [[UIApplication sharedApplication] openURL:[NSURL URLWithString:urlsting]];

    }];

    UIAlertAction* ownMapAction = [UIAlertAction actionWithTitle:NSLocalizedString(@"自带地图",nil)
                                                           style:UIAlertActionStyleDefault
                                                         handler:^(UIAlertAction* _Nonnull action) {

    MKMapItem* currentLocation  = [MKMapItem mapItemForCurrentLocation];
    MKMapItem* toLocation       = [[MKMapItem alloc] initWithPlacemark:[[MKPlacemark alloc]initWithCoordinate:self.coordinate addressDictionary:nil]];
    [MKMapItem openMapsWithItems:@[ currentLocation, toLocation ] launchOptions:@{
                                                                                  MKLaunchOptionsDirectionsModeKey : MKLaunchOptionsDirectionsModeDriving,
                                                                                  MKLaunchOptionsShowsTrafficKey : [NSNumber numberWithBool:YES]
                                                                                      }];
    }];

    [alerController addAction:cancelAction];
    if ([[UIApplication sharedApplication] canOpenURL:[NSURL URLWithString:@"baidumap://map/"]]) {
        [alerController addAction:baiduMapAction];
    }
    if ([[UIApplication sharedApplication] canOpenURL:[NSURL URLWithString:@"iosamap://"]]) {
        [alerController addAction:gaodeMapAction];
    };
    if ([[UIApplication sharedApplication] canOpenURL:[NSURL URLWithString:@"comgooglemaps://"]]) {
        [alerController addAction:googleMapAction];
    }
    [alerController addAction:ownMapAction];
    if (objc_getClass("UIAlertController") != nil) {
        [self presentViewController:alerController animated:YES completion:nil];
    }
    else {
//        UIAlertView* alert = [[UIAlertView alloc] initWithTitle:@"提示"
//                                                        message:@"请升级系统版本后用此功能"
//                                                       delegate:nil
//                                              cancelButtonTitle:@"确定"
//                                              otherButtonTitles:nil, nil];
//        [alert show];
    }
}

#pragma mark - 属性设置
- (NSMutableArray*)annotationaArray
{
    if (!_annotationaArray) {
        _annotationaArray = [[NSMutableArray alloc] init];
    }
    return _annotationaArray;
}

- (MKMapView*)mapview
{
    if (!_mapview) {
        _mapview = [[MKMapView alloc] initWithFrame:CGRectMake(0, 0, 300, 300)];
    }
    return _mapview;
}

- (AddressView *)addresView
{
    if (!_addresView) {
        _addresView       = [[AddressView alloc]init];
        _addresView.frame = CGRectMake(20, -52 - 64, SCREEN_WIDTH - 40, 52);
        [self.mapview addSubview:_addresView];
        [_addresView.navigationBtm addTarget:self action:@selector(mapNavigationBtn:) forControlEvents:UIControlEventTouchUpInside];
    }
    
    return _addresView;
}

@end
